package com.wjyf.reducing_bento.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.google.common.util.concurrent.RateLimiter;
import com.wjyf.reducing_bento.common.ErrorCode;
import com.wjyf.reducing_bento.exception.BusinessException;
import com.wjyf.reducing_bento.service.CodeService;
import com.wjyf.reducing_bento.utils.CaffeineUtils;
import com.wjyf.reducing_bento.utils.IPUtils;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import java.util.concurrent.TimeUnit;

import static com.wjyf.reducing_bento.constant.CaffeineKeyConstant.PHONE_CODE_KEY;

/**
 * @Author: lrk
 * @Date: 2023/4/1 下午 1:02
 * @Description:
 */
@Service
@Log4j2
public class CodeServiceImpl implements CodeService {

    @Resource
    private CaffeineUtils caffeineUtils;


    @Override
    public String getCode(String phone, HttpServletRequest request) {
        if (StringUtils.isBlank(phone)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String ip = IPUtils.getIpAddr(request);
        RateLimiter rateLimiter = caffeineUtils.getIp(ip);
        if (rateLimiter == null){
         throw new BusinessException(ErrorCode.OPERATION_ERROR, "操作太频繁");
        }
        final String PHONE_KEY = PHONE_CODE_KEY + phone;
        String cacheCode = caffeineUtils.getCode(PHONE_KEY);
        if (StringUtils.isNotBlank(cacheCode)){
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "请勿重复获取验证码");
        }
        String code = RandomUtil.randomNumbers(5);
        // 放进缓存
        caffeineUtils.putCode(PHONE_KEY, code);
        //TODO 整合阿里云发短信
        return code;
    }
}
